﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace TcpEchoSocketClient
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 7;
            IPAddress ip = IPAddress.Parse("192.168.1.2");
            string message = "Hello";
            byte[] buffer = Encoding.ASCII.GetBytes(message);
            Socket sock = null;

            try
            {
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint serverEndPoint = new IPEndPoint(ip, port);
                sock.Connect(serverEndPoint);
                Console.WriteLine("Connected to server");

                sock.Send(buffer, 0, buffer.Length, SocketFlags.None);
                Console.WriteLine("Message sent");

                int bytesRecived = 0;
                int totalBytesRecived = 0;

                while (totalBytesRecived < buffer.Length)
                {
                    if ((bytesRecived = sock.Receive(buffer,
                        totalBytesRecived, buffer.Length - totalBytesRecived, SocketFlags.None)) == 0)
                    {
                        Console.WriteLine("Connection closed prematurely");
                        break;
                    }
                    totalBytesRecived += bytesRecived;
                }

                sock.Close();

                Console.WriteLine("Recived message: {0}", Encoding.ASCII.GetString(buffer));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
